package com.example.myaptuselearing

import android.app.Activity
import com.example.myaptuselearing.annotation_introduce.BindViewRuntime
import com.example.myaptuselearing.bindview.BindAdapter
import java.lang.Exception

/**
 * @author tgw
 * @date 2021/9/30
 * @describe
 */
class MainActivityBindAdapterImp: BindAdapter<MainActivity> {

    override fun bind(activity: MainActivity) {
        activity.bt2 = activity.findViewById(R.id.bt_2)
    }


    /**运行时获取*/
    private  fun injectBindViewRuntime(activity: Activity) {
        try {
            //declaredFields 获取当前对象的所有属性
            val fields = activity.javaClass.declaredFields
            if (fields != null && fields.isNotEmpty()) {
                for (field in fields) {
                    //getAnnotation	返回该类中与参数类型匹配的公有注解对象
                    val viewInject: BindViewRuntime? = field.getAnnotation(BindViewRuntime::class.java)
                    //返回当前对象所有的公有注解对象
                    val annotations = field.annotations

                    viewInject?.let{viewInject ->
                        val viewId: Int = viewInject.value
                        try {
                            field.isAccessible = true
                            field[activity] = activity.findViewById(viewId)
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }
                    }

                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}